package com.dlc.shop.api.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.google.common.collect.Maps;
import com.dlc.shop.bean.app.param.SendSmsParam;
import com.dlc.shop.bean.enums.SendType;
import com.dlc.shop.bean.model.User;
import com.dlc.shop.common.enums.StatusEnum;
import com.dlc.shop.common.exception.YamiShopBindException;
import com.dlc.shop.common.response.ServerResponseEntity;
import com.dlc.shop.service.SmsLogService;
import com.dlc.shop.service.UserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Objects;

/**
 * @author LGH
 */
@RestController
@RequestMapping("/sms")
@Tag(name = "发送验证码接口")
@AllArgsConstructor
public class SmsController {

    private final SmsLogService smsLogService;
    private final UserService userService;

    @PostMapping("/sendLoginCode")
    @Operation(summary = "发送登录验证码" , description = "用户发送登录验证码")
    public ServerResponseEntity<Void> sendLoginCode(@RequestBody SendSmsParam sendSmsParam) {
        User user = userService.getOne(new LambdaQueryWrapper<User>().eq(User::getUserMobile, sendSmsParam.getMobile()));
        if(Objects.nonNull(user) && Objects.equals(user.getStatus(), StatusEnum.DISABLE.value())){
            // 用户已禁用，请联系客服
            throw new YamiShopBindException("yami.user.disabled");
        }
        // 每个手机号每分钟只能发十个注册的验证码，免得接口被利用
        smsLogService.sendSms(SendType.CAPTCHA, sendSmsParam.getMobile(), sendSmsParam.getMobile(), Maps.newLinkedHashMap());
        return ServerResponseEntity.success();
    }

    @PostMapping("/sendUpdatePwdCode")
    @Operation(summary = "发送修改密码验证码接口" , description = "发送修改密码验证码接口")
    public ServerResponseEntity<Void> sendUpdatePwdCode(@RequestBody SendSmsParam sendSmsParam) {
        // 每个手机号每分钟只能发十个注册的验证码，免得接口被利用
        smsLogService.sendSms(SendType.CAPTCHA, sendSmsParam.getMobile(), sendSmsParam.getMobile(), Maps.newLinkedHashMap());
        return ServerResponseEntity.success();
    }
}
